package com.wlz.security.page.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 *  自定义登陆页面
 */
//@Configuration
//@EnableWebSecurity 基于springboot 可以不用
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private UserDetailsService myUserDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()  //表单登录
                  // 自定义用户名和密码参数名 , 必须保证和前端表单的name值一致
//                .usernameParameter("user")
//                .passwordParameter("pwd")
                .loginPage("/login.html") //指定登录路径
                .loginProcessingUrl("/user/login")  // 对应 action="/user/login"
                .defaultSuccessUrl("/main.html");
        //.failureHandler()

        //授权
        http.authorizeRequests()
                // 不用认证
                .antMatchers("/login.html","/user/login").permitAll()
                .anyRequest().authenticated();  // 认证

         http.csrf().disable();//csrf关掉

    }

    @Bean
    public PasswordEncoder passwordEncoder(){
//        return NoOpPasswordEncoder.getInstance();
        return new BCryptPasswordEncoder();
    }


}
